/*
 * ArrayList.cpp
 *
 *  Created on: Dec 16, 2011
 *      Author: anna
 */

#include <iostream>
#include "Array.h"

using namespace std;

Array::Array(size_t capacity) {
	this->data = new int[capacity];
	this->capacity = capacity;
	this->actual_size = 0;
}

Array::Array(const Array& array) {
	this->data = new int[array.capacity];
	this->capacity = array.capacity;
	int array_size = array.actual_size;
	this->actual_size = array_size;
	for (int i = 0; i < array_size; i++) {
		this->data[i] = array.data[i];
	}
}

Array::~Array() {
	delete[] this->data;
}

Array& Array::operator =(const Array& array) {
	Array tmp(array);
	swap(this->actual_size, tmp.actual_size);
	swap(this->capacity, tmp.capacity);
	swap(this->data, tmp.data);
	return *this;
}

int Array::get(size_t index) const {
	if (index >= this->capacity) {
		throw "Index out of bounds";
	}
	return this->data[index];
}

size_t Array::size() const {
	return this->actual_size;
}

void Array::set(size_t index, int value) {
	this->ensure_capacity(index + 1);
	this->data[index] = value;
	if (index >= this->actual_size) {
		this->actual_size = index + 1;
	}
}

void Array::ensure_capacity(size_t min_capacity) {
	if (min_capacity > this->capacity) {
		this->capacity = this->capacity * 2;
		if (this->capacity < min_capacity) {
			this->capacity = min_capacity;
		}
		int *new_data = new int[this->capacity];
		for (size_t i = 0; i < this->capacity; i++) {
			new_data[i] = this->data[i];
		}
		delete[] this->data;
		this->data = new_data;
	}
}

void Array::push_back(int value) {
	this->set(this->actual_size, value);
}

int main() {
	Array a(5);
	a.set(10,5);
	cout << a.get(10) << "\n";
	a.push_back(11);
	cout << a.get(11) << "\n";
	return 0;
}

